package com.clusterswisdom.horn.servlet;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.clusterswisdom.horn.api.ioc.HornResponse;

@WebFilter(urlPatterns="/*")
public class HornFilter implements Filter {
	
	public static final String ENCODING = "UTF-8";
	
	public List<String> ips;

	@Override
	public void destroy() {}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		if (canAccess(request)) {
			request.setCharacterEncoding(ENCODING);
			response.setCharacterEncoding(ENCODING);
			chain.doFilter(request, response);
			
		} else {
			response.setContentType("application/json;charset=UTF-8");
			try {
				HornResponse hornResponse = new HornResponse(HornResponse.CODE_ERROR_INVOKE, "access permit", null);
				response.getWriter().write(JSON.toJSONString(hornResponse));
				response.getWriter().flush();
						
			} catch (IOException e) {
				e.printStackTrace();
				
			} 
			
		}
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		String ipsValue = config.getServletContext().getInitParameter("ips");
		if (ipsValue != null) {
			ips = Arrays.asList(ipsValue.split("[;]|[,]"));
		}
	}
	
	private boolean canAccess(ServletRequest request) {
		if (((HttpServletRequest)request).getRequestURI().indexOf("/defaultToken.jsp") != -1) {
			return true;
		}
		
		if (ips == null || ips.size() == 0) {
			return false;
		}
		
		return ips.contains(request.getRemoteAddr());
	}
}